<template>
    <div class="scale-view" ref="containerRef" :style="{overflow: containerOverflow}">
        <div class="content" :style="{
            height: `${height}px`,
            width: `${width}px`,
            transform: `translate(${transform.translateX}px,${transform.translateY}px) scale(${transform.scale})`
        }">
            <slot></slot>
        </div>
    </div>
</template>

<script lang="ts">
import {defineComponent, reactive, onMounted, onUnmounted, ref } from "vue";
export default defineComponent({
    props: {
        width: Number,
        height: Number
    },
    setup(props) {
        let containerOverflow = 'auto'
        const containerRef = ref<HTMLDivElement>()
        const transform = reactive({
            scale: 1,
            translateX: 0,
            translateY: 0
        })
        if (import.meta.env.PROD) {
            containerOverflow = 'hidden'
            const observer = new ResizeObserver(() => {
                const container = containerRef.value!
                const contentHeight = (props.height ?? container.clientHeight)
                const contentWidth = (props.width ?? container.clientWidth)
                const scaleRatioH = container.clientHeight / contentHeight
                const scaleRatioW = container.clientWidth / contentWidth
                transform.scale = Math.min(scaleRatioH, scaleRatioW)
                transform.translateX = Math.round((container.clientWidth - contentWidth) / 2)
                transform.translateY = Math.round((container.clientHeight - contentHeight) / 2)
            })
            onMounted(() => {
                observer.observe(containerRef.value!)
            })
            onUnmounted(() => {
                observer.disconnect()
            })
        }

        return {
            containerRef,
            transform,
            containerOverflow
        }
    }
})
</script>

<style scoped>
.content {
    position: relative;
    transform-origin: center center;
}
</style>